package com.jzt.gateway.utils;

import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpRequestDecorator;
import org.springframework.web.server.ServerWebExchange;

import java.util.ArrayList;

/**
 * 作者：lizw <br/>
 * 创建时间：2020/07/06 17:44 <br/>
 */
public class ExchangeUtils {

    /**
     * 为了能重写Cookies包装原始ServerHttpRequest
     */
    public static ServerWebExchange modifyRequestHeaders(ServerWebExchange exchange, ServerHttpRequest serverHttpRequest) {
        final HttpHeaders headers = new HttpHeaders();
        serverHttpRequest.getHeaders().forEach((name, values) -> headers.put(name, new ArrayList<>(values)));
        ServerHttpRequest newRequest = new ServerHttpRequestDecorator(serverHttpRequest) {
            @SuppressWarnings("NullableProblems")
            @Override
            public HttpHeaders getHeaders() {
                return headers;
            }
        };
        return exchange.mutate().request(newRequest).build();
    }
}
